
import 'package:flutter/material.dart';
import 'package:flutterxc/module/search_module.dart';
import 'package:flutterxc/widget/search_bar.dart';
import 'package:flutterxc/dao/search_dao.dart';
import 'package:flutterxc/widget/webview.dart';
import 'package:flutterxc/pages/speak_page.dart';

const String url =
    'https://m.ctrip.com/restapi/h5api/globalsearch/search?userid=M2208559994&source=mobileweb&action=mobileweb&keyword=';
const TYPES = [
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];

class SearchPage extends StatefulWidget {
  final bool hideLeft;
  final String searchUrl;
  final String keyword;
  final String hint;

//  final hideLeft;
  SearchPage(
      {Key key,
      this.hideLeft = false,
      this.searchUrl = url,
      this.keyword,
      this.hint = '搜索关键字'})
      : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  SearchModel _searchModel;
  String keyword;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.keyword != null) {
      _onTextChange(widget.keyword);
    }
//    String url = 'https://m.ctrip.com/restapi/h5api/searchapp/search?source=mobileweb&action=autocomplete&contentType=json&keyword=长城';
//    print(url);
//    SearchDao.fetch(url).then((res){
//      print('${res.data} 1111111');
//    }).catchError((err){
//      print('${err} 22222222');
//    });
  }

  _onTextChange(val) {
    keyword = val;
    if (val.length == 0) {
      setState(() {
        _searchModel = null;
      });
      return;
    }
    String urlVal = widget.searchUrl + val;
//    print(urlVal);
    SearchDao.fetch(urlVal, val: val).then((SearchModel res) {
//      print(res.keyword);
      if (res.keyword == keyword) {
//        print('${res.keyword} res.keyword');
        setState(() {
          _searchModel = res;
        });
      }
    }).catchError((err) {
      print('${err} 22222222');
    });

//    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[_appbar,
          MediaQuery.removePadding(
              context: context,
              removeTop: true,
              child: Expanded(
                flex: 1,
                child: ListView.builder(
                    itemCount: _searchModel?.data?.length ?? 0,
                    itemBuilder: (context, int index) {
                      return _item(index);
                    }),
              )
          )
        ],

//        child: _appbar,
      ),
    );
  }
  _jumToSpeak(){
    Navigator.push(context, MaterialPageRoute(builder: (context) => SpeakPage()));
  }
  get _appbar {
    return Column(
      children: <Widget>[
        SearchBar(
            enabled: true,
            hideLeft: widget.hideLeft,
            hint: widget.hint,
            speakClick: _jumToSpeak,
            onChanged: _onTextChange,
            defaultText: keyword,
            leftButtonClick: (){Navigator.pop(context);},
        ),
      ]

        );
  }

  _item(int index) {
//    print(_searchModel.data[index].districtname);
    if (_searchModel == null || _searchModel.data == null) return null;
    SearchItemModel item = _searchModel.data[index];
    return GestureDetector(
      onTap: (){
//        print(item.url);
        Navigator.push(context, MaterialPageRoute(builder: (context) => WebView(
          url: item.url,
          title: '详情',
        )));
      },
      child: Container(
        padding: EdgeInsets.all(8),
        decoration: BoxDecoration(
//          color: Colors.grey,
          border: Border(bottom: BorderSide(width: 0.3,color: Colors.grey))
        ),
        child: Row(
          children: <Widget>[
            Container(
            child: Image( image: AssetImage(_typeImage(item.type)),width: 25,height: 25,),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    child: _title(item),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 3),
                    child: _subtitle(item),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );

  }
   _title(SearchItemModel item){
    if (item == null) return null;
    List<TextSpan> spans = [];
    spans.addAll(_keywordTextSpans(item.word,_searchModel.keyword));
    spans.add(TextSpan(
        text: ' ' + (item.districtname ?? '') + ' ' + (item.zonename ?? ''),
        style: TextStyle(fontSize: 16,color: Colors.grey,)
    ));
    return RichText(text: TextSpan(children: spans),);
  }
  _subtitle(SearchItemModel item) {
//    if(item == null) return null;
//  print(item.star);
    return RichText(
      text: TextSpan(children:<TextSpan> [
        TextSpan(text: item.price ?? '',style: TextStyle(fontSize: 16,color: Colors.orange)),
        TextSpan(text: ' ' + (item.star ?? ''),style: TextStyle(fontSize: 14,color: Colors.grey))
      ]),
    );
  }
  _keywordTextSpans(String word,keyword){
    List<TextSpan> spans = [];
    if (word == null || word.length == 0) return spans;
//    搜索关键字忽略大小写
    String wordL = word.toLowerCase(),keywordL = keyword.toLowerCase();
//    根据关键字切割字符串 返回 一个 数组里
    List<String>arr = wordL.split(keywordL);
//    print('$arr $keyword');
//    普通字体
    TextStyle normalStyle = TextStyle(fontSize: 16,color: Colors.black87);
//    高亮关键字
    TextStyle keywordStyle = TextStyle(fontSize: 16,color: Colors.orange);
    int preIndex = 0;
    for(var i = 0 ; i < arr.length;i++) {
      if ((i+1) % 2 == 0) {
//        word.substring(preIndex,preIndex+1)
        spans.add(TextSpan(text: keyword,style: keywordStyle));
      }
      String val  = arr[i];
      if (val != null && val.length != 0) {
        spans.add(TextSpan(text: val,style: normalStyle));
      }
    }
    return spans;

  }
  _typeImage(String type) {
    if (type == null) return 'images/type_channelplane.png';
    String path = 'travelgroup';
    for (final val in TYPES) {
      if (type.contains(val)) {
        path = val;
        break;
      }
    }
//    print('$path');
    return 'images/type_$path.png';
  }
}
